<?php

namespace App\Controllers;

use App\Core\Request;
use App\Core\Response;
use App\Models\User;

class UserController
{
    public function index(): void
    {
        $page = (int) Request::get('page', 1);
        $pageSize = (int) Request::get('pageSize', 20);
        $offset = ($page - 1) * $pageSize;
        
        $users = User::findAll([], $pageSize, $offset);
        $total = User::count();
        
        // 移除密码字段
        foreach ($users as &$user) {
            unset($user['password']);
            $user['permissions'] = User::getUserPermissions($user['id']);
        }
        
        Response::paginate($users, $total, $page, $pageSize);
    }

    public function store(): void
    {
        $data = Request::validate([
            'username' => 'required',
            'password' => 'required|min:6',
            'real_name' => 'required',
            'role' => 'required'
        ]);
        
        // 检查用户名是否已存在
        if (User::findByUsername($data['username'])) {
            Response::error('用户名已存在', 400);
        }
        
        $permissions = Request::post('permissions', []);
        
        $userData = [
            'username' => $data['username'],
            'password' => $data['password'],
            'real_name' => $data['real_name'],
            'role' => $data['role'],
            'email' => Request::post('email'),
            'phone' => Request::post('phone')
        ];
        
        $id = User::createWithPermissions($userData, $permissions);
        
        Response::success(['id' => $id], '创建成功', 201);
    }

    public function update(string $id): void
    {
        $userId = (int) $id;
        
        if (!User::findById($userId)) {
            Response::error('用户不存在', 404);
        }
        
        $data = Request::all();
        unset($data['id'], $data['password'], $data['created_at'], $data['updated_at'], $data['permissions']);
        
        User::update($userId, $data);
        
        // 更新权限
        if (isset($_POST['permissions']) || isset(Request::getJsonData()['permissions'])) {
            $permissions = Request::post('permissions', []);
            User::updatePermissions($userId, $permissions);
        }
        
        Response::success(null, '更新成功');
    }

    public function destroy(string $id): void
    {
        $userId = (int) $id;
        
        if (!User::findById($userId)) {
            Response::error('用户不存在', 404);
        }
        
        // 不允许删除自己
        $currentUser = $GLOBALS['current_user'];
        if ($currentUser['id'] == $userId) {
            Response::error('不能删除当前登录用户', 400);
        }
        
        User::delete($userId);
        
        Response::success(null, '删除成功');
    }

    public function resetPassword(string $id): void
    {
        $userId = (int) $id;
        
        if (!User::findById($userId)) {
            Response::error('用户不存在', 404);
        }
        
        $data = Request::validate([
            'password' => 'required|min:6'
        ]);
        
        $hashedPassword = password_hash($data['password'], PASSWORD_DEFAULT);
        
        User::update($userId, ['password' => $hashedPassword]);
        
        Response::success(null, '密码重置成功');
    }
}

